package com.geek.water.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.MessageConstant;
import com.geek.water.entity.Customer;
import com.geek.water.entity.Site;
import com.geek.water.exception.WaterException;
import com.geek.water.result.Result;
import com.geek.water.service.AreaService;
import com.geek.water.service.CustomerService;
import com.geek.water.service.SiteService;
import com.geek.water.vo.PageQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/7/28
 */
@RestController
@RequestMapping("/admin/customer")
@RequiredArgsConstructor
@Api(tags = "后台系统-客户管理")
@Validated
public class CustomerController {

    private final CustomerService customerService;
    private final SiteService siteService;
    private final AreaService areaService;

    @ApiOperation("分页查询客户列表")
    @PreAuthorize("hasAuthority('customer:view')")
    @GetMapping("/page")
    public Result listCustomers(PageQueryVO queryVO) {
        Page<Customer> page = customerService.listCustomers(queryVO);
        if (page != null) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_CUSTOMER_SUCCESS, page);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.QUERY_CUSTOMER_FAIL);
    }

    @ApiOperation("新增客户")
    @PreAuthorize("hasAuthority('customer:operate')")
    @PostMapping
    public Result createCustomer( @RequestBody Customer customer) {

        customer.setStatus("active");
        boolean saved = customerService.save(customer);
        if (saved) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.ADD_CUSTOMER_SUCCESS);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.ADD_CUSTOMER_FAIL);
    }

    @ApiOperation("更新客户信息")
    @PreAuthorize("hasAuthority('customer:operate')")
    @PutMapping
    public Result updateCustomer( @RequestBody Customer customer) {
        boolean updated = customerService.updateById(customer);
        if (updated) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.UPDATE_CUSTOMER_SUCCESS);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.UPDATE_CUSTOMER_FAIL);
    }

    @ApiOperation("删除客户")
    @PreAuthorize("hasAuthority('customer:operate')")
    @DeleteMapping("/{id}")
    public Result deleteCustomer(@PathVariable Long id) {
        try {
            boolean success = customerService.deleteCustomerWithCheck(id);
            return success ?
                    new Result(CodeConstant.SUCCESS, MessageConstant.DELETE_CUSTOMER_SUCCESS) :
                    new Result(CodeConstant.FAIL, MessageConstant.DELETE_CUSTOMER_FAIL);
        } catch (WaterException e) {
            return new Result(CodeConstant.FAIL, e.getMessage());
        }
    }

    @ApiOperation("激活/停用客户")
    @PreAuthorize("hasAuthority('customer:status')")
    @PostMapping("/{id}/status")
    public Result changeStatus(@PathVariable Long id, @RequestParam String status) {
        if (!Arrays.asList("active", "suspended").contains(status)) {
            return new Result(CodeConstant.FAIL, "状态值无效");
        }

        Customer customer = new Customer();
        customer.setId(id);
        customer.setStatus(status);
        boolean updated = customerService.updateById(customer);
        if (updated) {
            return new Result(CodeConstant.SUCCESS, "状态更新成功");
        }
        return new Result(CodeConstant.FAIL, "状态更新失败");
    }

    @ApiOperation("获取客户列表（不分页）")
    @PreAuthorize("hasAuthority('customer:view')")
    @GetMapping("/list")
    public Result getCustomerList() {
        try {
            List<Customer> customers = customerService.list();
            return new Result(CodeConstant.SUCCESS, "获取客户列表成功", customers);
        } catch (Exception e) {
            return new Result(CodeConstant.FAIL, "获取客户列表失败: " + e.getMessage());
        }
    }

    @ApiOperation("获取客户下的站点列表")
    @PreAuthorize("hasAuthority('site:view')")
    @GetMapping("/{customerId}/sites")
    public Result getCustomerSites(@PathVariable Long customerId) {
        List<Site> sites = siteService.lambdaQuery()
                .eq(Site::getCustomerId, customerId)
                .list();
        if (!CollectionUtils.isEmpty(sites)) {
            return new Result(CodeConstant.SUCCESS, MessageConstant.QUERY_SITE_SUCCESS, sites);
        }
        return new Result(CodeConstant.FAIL, MessageConstant.QUERY_SITE_FAIL);
    }
}
